package com.wang.mvchain.outer.service.implay;

import java.math.BigDecimal;
import java.util.Base64;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Random;
import java.util.TreeMap;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wang.mvchain.common.util.ConstatFinalUtil;
import com.wang.mvchain.common.util.EncryptUtil;
import com.wang.mvchain.common.util.HTTPUtil;
import com.wang.mvchain.outer.service.ITradeService;

/**
 * bitfinex的API工具
 * 
 * 支持的币种:["btcusd","ltcusd","ltcbtc","drkusd","drkbtc","th1btc"]
 * 
 * @author wangsh
 *
 */
public class BitfinexTradeServiceImplay extends BaseTradeService implements ITradeService
{
	//登陆验证的信息,可从网站模板中查找
	private JSONObject authJSON;
	
	@Override
	public int findWebsiteId()
	{
		return 7;
	}
	
	/**
	 * 获取签名方式
	 * 
	 * @return
	 */
	private String authSign(Map<String, Object> condMap)
	{
		String reqJSONStr = Base64.getEncoder().encodeToString(JSONObject.toJSONString(condMap).getBytes());
		//System.out.println("request:"+JSONObject.toJSONString(condMap));
		condMap.clear();
		condMap.put("X-BFX-PAYLOAD", reqJSONStr + "");
		return EncryptUtil.hmacSHA384(reqJSONStr, authJSON.get("Secret") + "");
	}
	/**
	 * 获取用户基本信息
	 * 
	 * @return
	 */
	public JSONObject getUserInfo(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		String nonce = this.findReqtime() ;
		
		String method = "/balances";
		Map<String, String> requestMap = new HashMap<String, String>();
		Map<String, Object> cloneMap = new HashMap<String, Object>();
		HTTPUtil httpUtil = new HTTPUtil();
		cloneMap.put("request","/v1" + method);
		cloneMap.put("nonce", nonce);
		
		Map<String, String> headerMap = new HashMap<String, String>();
		String sign = this.authSign(cloneMap);
		headerMap.put("X-BFX-APIKEY", authJSON.get("Key") + "");
		headerMap.put("X-BFX-PAYLOAD", cloneMap.get("X-BFX-PAYLOAD") + "");
		headerMap.put("X-BFX-SIGNATURE", sign);
		
		requestMap.clear();
		requestMap.put("requestURL", "https://api.bitfinex.com/v1" + method);
		
		JSONArray responseJSON = new JSONArray();
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(headerMap, requestMap);
//			ConstatFinalUtil.SYS_LOG.info(res + "------>");
			responseJSON = (JSONArray) JSON.parse(result);
			JSONObject dataJSON = new JSONObject();
			
			JSONObject fundJSON = new JSONObject();
			fundJSON.put("btc", "0");
			fundJSON.put("ltc", "0");
			fundJSON.put("eth", "0");
			fundJSON.put("etc", "0");
			//fundJSON.put("cny", "0");
			fundJSON.put("usd", "0");
			
			JSONObject balanceJSON = new JSONObject();
			for(Object item:responseJSON){
				JSONObject itemJSON= (JSONObject) item;
				balanceJSON.put(itemJSON.getString("currency"),itemJSON.getString("available"));
			}
			
			if(balanceJSON.get("usd") == null)
			{
				balanceJSON.put("usd","0");
			}
			
			if(balanceJSON.get("btc") == null)
			{
				balanceJSON.put("btc","0");
			}
			
			if(balanceJSON.get("ltc") == null)
			{
				balanceJSON.put("ltc","0");
			}
			
			if(balanceJSON.get("eth") == null)
			{
				balanceJSON.put("eth","0");
			}
			
			if(balanceJSON.get("etc") == null)
			{
				balanceJSON.put("etc","0");
			}
			
			dataJSON.put("balance", balanceJSON);
			dataJSON.put("fund", fundJSON);
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			/*ConstatFinalUtil.OUTER_LOG.info(this.findid() + "--获取用户信息返回.--原始信息:" + responseJSON
					+ ";转换后目标信息:" + resultJSON);
			*/
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取用户信息失败;nonce:" + nonce + ";"
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 下单交易
		New order
		POST /order/new
		Submit a new order.
		Request
		
		symbol (string): The name of the symbol (see `/symbols`).
		amount (decimal): Order size: how much to buy or sell.
		price (price): Price to buy or sell at. Must be positive. Use random number for market orders.
		exchange (string): "bitfinex".
		side (string): Either "buy" or "sell".
		type (string): Either "market" / "limit" / "stop" / "trailing-stop" / "fill-or-kill" / "exchange market" / "exchange limit" / "exchange stop" / "exchange trailing-stop" / "exchange fill-or-kill". (type starting by "exchange " are exchange orders, others are margin trading orders) 
		is_hidden (bool) true if the order should be hidden. Default is false.
		{
		   "id":4003264,
		   "symbol":"btcusd",
		   "exchange":"bitfinex",
		   "price":"900.0",
		   "avg_execution_price":"0.0",
		   "side":"sell",
		   "type":"exchange limit",
		   "timestamp":"1387061558.610016778",
		   "is_live":true,
		   "is_cancelled":false,
		   "was_forced":false,
		   "original_amount":"0.01",
		   "remaining_amount":"0.01",
		   "executed_amount":"0.0",
		   "order_id":4003264
		}		
	 * @return
	 */
	public JSONObject trade(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		//开发版本
		if("1".equalsIgnoreCase(ConstatFinalUtil.SYS_BUNDLE.getString("dev.version")))
		{
			//模拟假数据
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("order_id", new Random().nextInt(10000));
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "---模拟下单---" + paramsMap);
			return resultJSON ; 
		}
		
		String nonce = this.findReqtime() ;
		String method = "/order/new";
		Map<String, String> requestMap = new HashMap<String, String>();
		Map<String, Object> cloneMap = new HashMap<String, Object>();
		HTTPUtil httpUtil = new HTTPUtil();
		cloneMap.put("request","/v1" + method);
		cloneMap.put("nonce", nonce);
		
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		cloneMap.put("symbol", moneytype);
		cloneMap.put("amount", paramsMap.get("amount"));
		cloneMap.put("price", paramsMap.get("price"));
		cloneMap.put("exchange", "bitfinex");
		// 买还是卖.0:买,1:卖
		if ("0".equalsIgnoreCase(paramsMap.get("type")))
		{
			cloneMap.put("side", "buy");
		} else if ("1".equalsIgnoreCase(paramsMap.get("type")))
		{
			cloneMap.put("side", "sell");
		}
		//TODO 填limit报错:not enough balance
		cloneMap.put("type", "exchange limit");
		//TODO 填false报错:Key is_hidden was not present
		//cloneMap.put("is_hidden", true);
		Map<String, String> headerMap = new HashMap<String, String>();
		String sign = this.authSign(cloneMap);
		headerMap.put("X-BFX-APIKEY", authJSON.get("Key") + "");
		headerMap.put("X-BFX-PAYLOAD", cloneMap.get("X-BFX-PAYLOAD") + "");
		headerMap.put("X-BFX-SIGNATURE", sign);
		
		requestMap.clear();
		requestMap.put("requestURL", "https://api.bitfinex.com/v1" + method);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			
			if(responseJSON.containsKey("order_id"))
			{
				JSONObject returnJSON = (JSONObject) responseJSON.get("return");
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", responseJSON.get("order_id"));
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--下单交易返回--nonce:" + nonce + ";原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "下单交易失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 撤销订单
		Cancel order
		POST /order/cancel
		Cancel an order.
		Request
		
		order_id (int): The order ID given by `/order/new`.
		Response
		
		Result of /order/status for the cancelled order
	 	{
		   "id":4003242,
		   "symbol":"btcusd",
		   "exchange":null,
		   "price":"900.0",
		   "avg_execution_price":"0.0",
		   "side":"sell",
		   "type":"exchange limit",
		   "timestamp":"1387061342.0",
		   "is_live":false,
		   "is_cancelled":true,
		   "was_forced":false,
		   "original_amount":"0.01",
		   "remaining_amount":"0.01",
		   "executed_amount":"0.0"
		}
	 * @return
	 */
	public JSONObject cancelOrder(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		//开发版本
		if("1".equalsIgnoreCase(ConstatFinalUtil.SYS_BUNDLE.getString("dev.version")))
		{
			//模拟假数据
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("order_id", paramsMap.get("order_id"));
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "---模拟下单---" + paramsMap);
			return resultJSON ; 
		}
		
		String nonce = this.findReqtime() ;
		String method = "/order/cancel";
		Map<String, String> requestMap = new HashMap<String, String>();
		Map<String, Object> cloneMap = new HashMap<String, Object>();
		HTTPUtil httpUtil = new HTTPUtil();
		cloneMap.put("request","/v1" + method);
		cloneMap.put("nonce", nonce);
		cloneMap.put("order_id", new BigDecimal(paramsMap.get("order_id")).intValue());
		Map<String, String> headerMap = new HashMap<String, String>();
		String sign = this.authSign(cloneMap);
		headerMap.put("X-BFX-APIKEY", authJSON.get("Key") + "");
		headerMap.put("X-BFX-PAYLOAD", cloneMap.get("X-BFX-PAYLOAD") + "");
		headerMap.put("X-BFX-SIGNATURE", sign);
		requestMap.clear();
		requestMap.put("requestURL", "https://api.bitfinex.com/v1" + method);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap , requestMap);
			responseJSON = (JSONObject) JSON.parse(result);
			//ConstatFinalUtil.SYS_LOG.info("=--==>" + response);
			if(responseJSON.containsKey("id") && "true".equalsIgnoreCase(responseJSON.get("is_cancelled") + ""))
			{
				JSONObject returnJSON = (JSONObject) responseJSON.get("return");
				JSONObject dataJSON = new JSONObject();
				dataJSON.put("order_id", paramsMap.get("order_id"));
				//dataJSON.put("id", responseJSON.getInteger("id"));
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("message"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--撤销订单返回.--;nonce:" + nonce + ";原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "撤销订单失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * 获取用户挂单
	 * 
	 * {
			"success":1,
			"return":{
				"343152":{
					"pair":"btc_usd",
					"type":"sell",
					"amount":12.345,
					"rate":485,
					"timestamp_created":1342448420,
					"status":0
				},
				...
			}
		}
	 * 
	 * @param args
		Active Orders
		POST /orders
		View your active orders.
		Response
		
		An array of the results of `/order/status` for all your live orders.
		[
		   {
		      "id":4003242,
		      "symbol":"btcusd",
		      "exchange":null,
		      "price":"900.0",
		      "avg_execution_price":"0.0",
		      "side":"sell",
		      "type":"exchange limit",
		      "timestamp":"1387061342.0",
		      "is_live":true,
		      "is_cancelled":false,
		      "was_forced":false,
		      "original_amount":"0.08",
		      "remaining_amount":"0.06",
		      "executed_amount":"0.02"
		   },,,
		]
	 */
	public JSONObject getOrders(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		//开发版本
		if("1".equalsIgnoreCase(ConstatFinalUtil.SYS_BUNDLE.getString("dev.version")))
		{
			//模拟假数据
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("ordersList", new JSONArray());
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "---模拟下单---" + paramsMap);
			return resultJSON ; 
		}
		
		String nonce = this.findReqtime() ;
		String method = "/orders";
		Map<String, String> requestMap = new HashMap<String, String>();
		Map<String, Object> cloneMap = new HashMap<String, Object>();
		HTTPUtil httpUtil = new HTTPUtil();
		cloneMap.put("request","/v1" + method);
		cloneMap.put("nonce", nonce);
		Map<String, String> headerMap = new HashMap<String, String>();
		String sign = this.authSign(cloneMap);
		headerMap.put("X-BFX-APIKEY", authJSON.get("Key") + "");
		headerMap.put("X-BFX-PAYLOAD", cloneMap.get("X-BFX-PAYLOAD") + "");
		headerMap.put("X-BFX-SIGNATURE", sign);
		
		requestMap.clear();
		requestMap.put("requestURL", "https://api.bitfinex.com/v1" + method);
		
		JSONArray responseJSON = new JSONArray();
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, requestMap);
			responseJSON = (JSONArray) JSON.parse(result);
			JSONObject dataJSON = new JSONObject();
			
			JSONArray ordersResArr = new JSONArray();
			for (Object order:responseJSON)
			{
				JSONObject valJSON = (JSONObject) order;
				
				JSONObject ordersResJSON = new JSONObject();
				ordersResJSON.put("order_id", valJSON.get("id")+"");
				ordersResJSON.put("price", valJSON.get("price") + "");
				ordersResJSON.put("amount", valJSON.get("original_amount") + "");
				ordersResJSON.put("deal_amount", valJSON.get("executed_amount") + "");
				
				//处理下单时间
				Date createDate = new Date(Double.valueOf(valJSON.get("timestamp") + "").longValue() * 1000);
				ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
				
				String pair = valJSON.get("symbol") + "";
				pair = this.convertMoneyType(pair);
				ordersResJSON.put("symbol", pair);
				String side = valJSON.get("side") + "";
				if("buy".equalsIgnoreCase(side))
				{
					side = "0" ; 
				}else if("sell".equalsIgnoreCase(side))
				{
					side = "1" ; 
				}
				ordersResJSON.put("type", side);
				//TODO 不确定
				ordersResJSON.put("status", valJSON.get("is_live") + "");
				
				ordersResArr.add(ordersResJSON);
			}
			
			dataJSON.put("ordersList", ordersResArr);
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取订单信息.--;nonce:" + nonce + ";原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取订单信息失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}
	
	/**
	 * 行情API
		Ticker
		GET /pubticker/:symbol
		Gives innermost bid and asks and information on the most recent trade, as well as high, low and volume of the last 24 hours.
		Response:
		mid (price): (bid + ask) / 2
		bid (price): Innermost bid.
		ask (price): Innermost ask.
		last_price (price) The price at which the last order executed.
		low (price): Lowest trade price of the last 24 hours
		high (price): Highest trade price of the last 24 hours
		volume (price): Trading volume of the last 24 hours
		timestamp (time) The timestamp at which this information was valid.
		{
		   "mid":"522.935",
		   "bid":"522.2",
		   "ask":"523.67",
		   "last_price":"523.67",
		   "low":"514.25",
		   "high":"532.74",
		   "volume":"6533.86438038",
		   "timestamp":"1400949917.858329958"
		}		
	 */
	public JSONObject queryTicker(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		
		String nonce = this.findReqtime() ; 
		String method = "/pubticker/"+paramsMap.get("symbol");
		Map<String, String> requestMap = new HashMap<String, String>();
		Map<String, Object> cloneMap = new HashMap<String, Object>();
		HTTPUtil httpUtil = new HTTPUtil();
		cloneMap.put("request","/v1" + method);
		cloneMap.put("nonce", nonce);
		Map<String, String> headerMap = new HashMap<String, String>();
		String sign = this.authSign(cloneMap);
		headerMap.put("X-BFX-APIKEY", authJSON.get("Key") + "");
		headerMap.put("X-BFX-PAYLOAD", cloneMap.get("X-BFX-PAYLOAD") + "");
		headerMap.put("X-BFX-SIGNATURE", sign);
		
		requestMap.clear();
		requestMap.put("requestURL", "https://api.bitfinex.com/v1" + method);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(headerMap, requestMap);
			//ConstatFinalUtil.SYS_LOG.info(result + "------>");
			responseJSON = (JSONObject) JSON.parse(result);
			if(responseJSON.containsKey("timestamp"))
			{
				JSONObject dataJSON = new JSONObject();
				
				resultJSON.put("data", dataJSON);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.get("error"));
			}
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取Ticker返回.--" + responseJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取Ticker失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * depth(市场深度)
		Orderbook
		GET /book/:symbol
		Get the full order book.
		Request:
		
		limit_bids (int): Optional. Limit the number of bids returned. May be 0 in which case the array of bids is empty. Default is 50. 
		limit_asks (int): Optional. Limit the number of asks returned. May be 0 in which case the array of asks is empty. Default is 50. 
		group (0/1): Optional. If 1, orders are grouped by price in the orderbook. If 0, orders are not grouped and sorted individually. Default is 1
		Response
		
		bids (array)
		price (price)
		amount (decimal)
		timestamp (time)
		asks (array)
		price (price)
		amount (decimal)
		timestamp (time)
		{
		   "bids":[
		      {
		         "price":"849.59",
		         "amount":"0.08",
		         "timestamp":"1387058276.0"
		      },,,
		   ],
		   "asks":[
		      {
		         "price":"851.87",
		         "amount":"0.179977",
		         "timestamp":"1387060950.0"
		      },,,
		   ]
		}		
	 */
	public JSONObject queryDepth(Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		
		String moneytype = this.convertMoneyType(paramsMap.get("moneytype"));
		
		String method = "/book/"+moneytype+"/";
		Map<String, String> requestMap = new HashMap<String, String>();
		HTTPUtil httpUtil = new HTTPUtil();
		requestMap.put("requestURL", "https://api.bitfinex.com/v1" + method);
		
		JSONObject responseJSON = new JSONObject();
		String result = "" ; 
		try
		{
			result = httpUtil.methodGet(requestMap);
			//ConstatFinalUtil.OUTER_LOG.error(res);
			responseJSON = (JSONObject) JSON.parse(result);

			// 拼装符合条件的json数据
			JSONObject dataJSON = new JSONObject();

			int count = 0;
			// 按照规则排序的容器
			Map<Double, JSONObject> asksMap = new TreeMap<Double, JSONObject>();
			JSONArray asksResArr = new JSONArray();
			JSONArray asksArr = (JSONArray) responseJSON.get("asks");
			for (Object item:asksArr)
			{
				JSONObject askJSON = (JSONObject) item;
				askJSON.put("count", "1");
				askJSON.put("vol", askJSON.get("amount")+"");
				askJSON.put("rate", askJSON.get("price")+"");

				asksMap.put(Double.valueOf(askJSON.get("rate") + ""), askJSON);
			}

			for (Iterator iterator = asksMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject asksTemp = (JSONObject) me.getValue();

				asksResArr.add(asksTemp);
				count++;
			}

			dataJSON.put("asks", asksResArr);

			// 按照规则排序的容器
			count = 0;
			Map<Double, JSONObject> bidsMap = new TreeMap<Double, JSONObject>(
					new Comparator<Double>()
					{
						@Override
						public int compare(Double o1, Double o2)
						{
							return o2.compareTo(o1);
						}
					});
			JSONArray bidsResArr = new JSONArray();
			JSONArray bidsArr = (JSONArray) responseJSON.get("bids");
			for (Object item:bidsArr)
			{
				JSONObject bidsJSON = (JSONObject) item;
				bidsJSON.put("count", "1");
				bidsJSON.put("vol", bidsJSON.get("amount") + "");
				bidsJSON.put("rate", bidsJSON.get("price") + "");

				bidsMap.put(Double.valueOf(bidsJSON.get("rate") + ""), bidsJSON);
			}

			for (Iterator iterator = bidsMap.entrySet().iterator(); iterator
					.hasNext();)
			{
				Entry me = (Entry) iterator.next();
				double key = (Double) me.getKey();

				if (count >= ConstatFinalUtil.PAGE_BATCH_SIZE)
				{
					break;
				}

				JSONObject bidsTemp = (JSONObject) me.getValue();

				bidsResArr.add(bidsTemp);
				count++;
			}
			dataJSON.put("bids", bidsResArr);

			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			resultJSON.put("data", dataJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取深度失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	/**
	 * trades的格式,历史交易记录
		Past trades
		POST /mytrades
		View your past trades
		Request
		
		symbol (string): The pair traded (BTCUSD, LTCUSD, LTCBTC).
		timestamp (time): Trades made before this timestamp won't be returned.
		limit_trades (int): Optional. Limit the number of trades returned. Default is 50.
		Response
		
		An array of dictionaries:
		price (price)
		amount (decimal)
		timestamp (time)
		exchange (string)
		type (string) Sell or Buy
		fee_currency (string) Currency you paid this trade's fee in
		fee_amount (decimal) Amount of fees you paid for this trade
		tid (integer) unique identification number of the trade
		order_id (integer) unique identification number of the parent order of the trade
		[
		   {
		      "price":"854.01",
		      "amount":"0.0072077",
		      "timestamp":"1387057315.0",
		      "exchange":"bitfinex",
		      "type":"Sell"
		   },,,
		]		
	 */
	public JSONArray queryHistoryTrades(String symbol,
			Map<String, String> paramsMap)
	{
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		
		String nonce = this.findReqtime() ; 
		String method = "/mytrades";
		Map<String, String> requestMap = new HashMap<String, String>();
		Map<String, Object> cloneMap = new HashMap<String, Object>();
		HTTPUtil httpUtil = new HTTPUtil();
		cloneMap.put("request","/v1" + method);
		cloneMap.put("nonce", nonce);
		cloneMap.put("symbol", symbol);
		cloneMap.put("timestamp", new BigDecimal(paramsMap.get("timestamp")).longValue());
		cloneMap.put("limit_trades", new BigDecimal(paramsMap.get("limit_trades")).intValue());
		Map<String, String> headerMap = new HashMap<String, String>();
		String sign = this.authSign(cloneMap);
		headerMap.put("X-BFX-APIKEY", authJSON.get("Key") + "");
		headerMap.put("X-BFX-PAYLOAD", cloneMap.get("X-BFX-PAYLOAD") + "");
		headerMap.put("X-BFX-SIGNATURE", sign);
		
		requestMap.clear();
		requestMap.put("requestURL", "https://api.bitfinex.com/v1" + method);
		
		JSONArray responseJSON = new JSONArray();
		String result = "" ; 
		try
		{
			result = httpUtil.methodPost(headerMap, requestMap);
			//ConstatFinalUtil.SYS_LOG.info(res + "------>");
			responseJSON = (JSONArray) JSON.parse(result);
			if(responseJSON.size()>0)
			{
				JSONArray mairuArr = new JSONArray();
				for(Object item:responseJSON){
					JSONObject itemJSON = (JSONObject) item;
					if(itemJSON.getString("type").equals("Buy")){
						JSONObject mairuTempJSON = new JSONObject();
						// 1买入
						mairuTempJSON.put("type", "1");
						mairuTempJSON.put("price", itemJSON.getString("price"));
						mairuTempJSON.put("num", itemJSON.getString("amount"));
						mairuArr.add(mairuTempJSON);
					}
					
				}
				resultJSON.put("mairu", mairuArr);
				JSONArray maichuArr = new JSONArray();
				for(Object item:responseJSON){
					JSONObject itemJSON = (JSONObject) item;
					if(itemJSON.getString("type").equals("Sell")){
						JSONObject maichuTempJSON = new JSONObject();
						// 0卖出
						maichuTempJSON.put("type", "0");
						maichuTempJSON.put("price", itemJSON.getString("price"));
						maichuTempJSON.put("num", itemJSON.getString("amount"));
						maichuArr.add(maichuTempJSON);
					}
					
				}
				resultJSON.put("maichu", maichuArr);
				resultJSON.put("code", "0");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			}else
			{
				resultJSON.put("code", "-6");
				resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-6") + ";返回数据:" + responseJSON.toJSONString());
			}
			//ConstatFinalUtil.OUTER_LOG.info(this.findid() + "--获取历史交易记录返回.--" + responseJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "历史交易记录失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return null;
	}


	public void setAuthJSON(JSONObject authJSON)
	{
		this.authJSON = authJSON;
	}

	@Override
	public String convertMoneyType(String moneytype)
	{
		String converted = "";
		if(moneytype.equals("btc_usd")){
			converted="btcusd";
		}else if(moneytype.equals("ltc_usd")){
			converted="ltcusd";
		}else if(moneytype.equals("ltc_btc")){
			converted="ltcbtc";
		}else if(moneytype.equals("drk_usd")){
			converted="drkusd";
		}else if(moneytype.equals("drk_btc")){
			converted="drkbtc";
		}else if(moneytype.equals("th1_btc")){
			converted="th1btc";
		}else if(moneytype.equals("eth_usd")){
			converted="ethusd";
		}else if(moneytype.equals("etc_usd")){
			converted="etcusd";
		}
		return converted;
	}

	@Override
	public String toString()
	{
		return "BitfinexTradeServiceImplay [findid()=" + findWebsiteId() + "]";
	}
	
	/**
	 * 返回结果:
	 * var response = {
		"id" : 999218359,
		"symbol" : "ethusd",
		"exchange" : "bitfinex",
		"price" : "400.22",
		"avg_execution_price" : "0.0",
		"side" : "sell",
		"type" : "exchange limit",
		"timestamp" : "1471168536.0",
		"is_live" : true,
		"is_cancelled" : false,
		"is_hidden" : false,
		"oco_order" : null,
		"was_forced" : false,
		"original_amount" : "0.1",
		"remaining_amount" : "0.1",
		"executed_amount" : "0.0"
	}
	 */
	@Override
	public JSONObject getOrdersSingle(Map<String, String> paramsMap)
	{
		String orderid = paramsMap.get("order_id");
		long st = System.currentTimeMillis() ; 
		//拼装目标数据
		JSONObject resultJSON = new JSONObject();
		//开发版本
		if("1".equalsIgnoreCase(ConstatFinalUtil.SYS_BUNDLE.getString("dev.version")))
		{
			//模拟假数据
			JSONObject dataJSON = new JSONObject();
			dataJSON.put("ordersList", new JSONArray());
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "---模拟下单---" + paramsMap);
			return resultJSON ; 
		}
		
		String nonce = this.findReqtime() ;
		String method = "/order/status";
		Map<String, String> requestMap = new HashMap<String, String>();
		Map<String, Object> cloneMap = new HashMap<String, Object>();
		HTTPUtil httpUtil = new HTTPUtil();
		cloneMap.put("request","/v1" + method);
		cloneMap.put("order_id",Integer.valueOf(orderid));
		cloneMap.put("nonce", nonce);
		Map<String, String> headerMap = new HashMap<String, String>();
		String sign = this.authSign(cloneMap);
		headerMap.put("X-BFX-APIKEY", authJSON.get("Key") + "");
		headerMap.put("X-BFX-PAYLOAD", cloneMap.get("X-BFX-PAYLOAD") + "");
		headerMap.put("X-BFX-SIGNATURE", sign);
		
		requestMap.clear();
		requestMap.put("requestURL", "https://api.bitfinex.com/v1" + method);
		
		String result = "" ; 
		try
		{
			result = httpUtil.methodHttpsPost(headerMap, requestMap);
			JSONObject valJSON = (JSONObject) JSON.parse(result);
			
			JSONObject dataJSON = new JSONObject();
			if(orderid.equalsIgnoreCase(valJSON.get("id") + ""))
			{
				JSONObject ordersResJSON = new JSONObject();
				ordersResJSON.put("order_id", valJSON.get("id")+"");
				ordersResJSON.put("price", valJSON.get("price") + "");
				ordersResJSON.put("amount", valJSON.get("original_amount") + "");
				ordersResJSON.put("deal_amount", valJSON.get("executed_amount") + "");
				
				//处理下单时间
				Date createDate = new Date(Double.valueOf(valJSON.get("timestamp") + "").longValue() * 1000);
				ordersResJSON.put("create_date", this.dateUtil.formatDateTime(createDate));
				
				String pair = valJSON.get("symbol") + "";
				pair = this.parseMoneyType(pair);
				ordersResJSON.put("symbol", pair);
				String side = valJSON.get("side") + "";
				if("buy".equalsIgnoreCase(side))
				{
					side = "0" ; 
				}else if("sell".equalsIgnoreCase(side))
				{
					side = "1" ; 
				}
				ordersResJSON.put("type", side);
				//TODO 不确定
				String status = "" ; 
				if("true".equalsIgnoreCase(valJSON.get("is_cancelled") + ""))
				{
					status = "-1";
				}else if("true".equalsIgnoreCase(valJSON.get("is_live") + ""))
				{
					status = "0" ;
				}
				ordersResJSON.put("status", status + "");
				dataJSON.put("orders", ordersResJSON);
			}
			
			resultJSON.put("data", dataJSON);
			resultJSON.put("code", "0");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("0"));
			
			ConstatFinalUtil.OUTER_LOG.info(this.findWebsiteId() + "--获取订单详情.--;nonce:" + nonce + ";原始信息:" + result
					+ ";转换后目标信息:" + resultJSON);
		} catch (Exception e)
		{
			ConstatFinalUtil.OUTER_LOG.error(this.findWebsiteId() + "获取订单详情失败."
					+ requestMap + ";原始信息:" + result , e);
			resultJSON.put("code", "-1");
			resultJSON.put("info", ConstatFinalUtil.INFO_JSON.get("-1"));
		}
		long ed = System.currentTimeMillis() ;
		resultJSON.put("consume", (ed -st) + "毫秒");
		return resultJSON;
	}

	@Override
	public String parseMoneyType(String moneytype)
	{
		String converted = moneytype;
		if(moneytype.equals("btcusd")){
			converted="btc_usd";
		}else if(moneytype.equals("ltcusd")){
			converted="ltc_usd";
		}else if(moneytype.equals("ltcbtc")){
			converted="ltc_btc";
		}else if(moneytype.equals("drkusd")){
			converted="drk_usd";
		}else if(moneytype.equals("drkbtc")){
			converted="drk_btc";
		}else if(moneytype.equals("th1btc")){
			converted="th1_btc";
		}else if(moneytype.equals("ethusd")){
			converted="eth_usd";
		}
		return converted;
	}

	@Override
	public String findWebSiteName()
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public JSONObject convertOrders(String moneytype, JSONObject ordersTemp)
	{
		// TODO Auto-generated method stub
		return null;
	}
}
